import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/inv_list_entity.dart';
import 'package:xiongan_app_yy/entrys/rp/warehousing_returns_entity.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/pages/common/LoadBuilder.dart';
import 'package:xiongan_app_yy/widgets/comm/label_select.dart';
import 'package:xiongan_app_yy/widgets/comm/left_icon_widget.dart';
import 'package:xiongan_app_yy/widgets/in_task_list_widget.dart';

//信息-入库退货
class WarehousingReturns extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return WarehousingReturnsState();
  }
}

class WarehousingReturnsState extends State<WarehousingReturns> {
  var _futureBuilderFuture;
  String data;
  WarehousingReturnsEntity bean;
  int size = 0;
  List<WarehousingReturnsData> exhibitionList = new List();
  List<String> _labelText = [
    '未退货',
    '已退货',
    '已驳回',
  ];
  int selected = -1;

  Iterable<Widget> get _inputSelects sync* {
    for (int i = 0; i < _labelText.length; i++) {
      yield InputSelect(
        index: i,
        choice: _labelText[i],
        parent: this,
      );
    }
  }

  onSelectedChanged(int index) {
    setState(() {
      selected = index;
    });
  }

  @override
  void initState() {
    super.initState();
    _futureBuilderFuture = _gerData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        endDrawer: Drawer(
          child: Container(
            padding: EdgeInsets.only(left: 10, right: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                    margin: EdgeInsets.only(top: 80, bottom: 10),
                    child: Text("入库状态",
                        style:
                            TextStyle(fontSize: 14, color: Color(0xFF646464)))),
                Expanded(
                  child: Wrap(
                    children: _inputSelects.toList(),
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(bottom: 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        FlatButton(
                            onPressed: () {
                              Navigator.pop(context);
                              setState(() {
                                selected = -1;
                              });
                            },
                            child: Text(
                              "重置",
                              style: TextStyle(color: Color(0xFF00A5F1)),
                            ),
                            color: Color(0xFFE9E9E9),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(20),
                                    topLeft: Radius.circular(20)))),
                        FlatButton(
                            onPressed: () {
                              setState(() {});
                              Navigator.pop(context);
                            },
                            child: Text(
                              "确定",
                              style: TextStyle(color: Colors.white),
                            ),
                            color: Color(0xFF00A5F1),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.only(
                                    bottomRight: Radius.circular(20),
                                    topRight: Radius.circular(20))))
                      ],
                    ))
              ],
            ),
          ),
        ),
        appBar: new AppBar(
          leading: LeftIconWidget(icon: Icons.chevron_left, isize: 36),
          backgroundColor: Color(0XFF00A5F1),
          title: Text(
            "入库退货",
            style: TextStyle(fontSize: 18),
          ),
          actions: <Widget>[
            new IconButton(
              // action button
              padding: EdgeInsets.only(),
              iconSize: 22,
              icon: new Icon(IconData(0xe617, fontFamily: "wuIconFont")),
              onPressed: () {
                Navigator.pushNamed(context, '/warehousingReturnSearch');
              },
            ),
            Builder(
              builder: (context) => new IconButton(
                // action button
                iconSize: 18,
                icon: new Icon(IconData(0xe621, fontFamily: "wuIconFont")),
                onPressed: () {
                  Scaffold.of(context).openEndDrawer();
                },
              ),
            ),
          ],
          elevation: 0,
          centerTitle: true,
        ),
        body: FutureBuilder(
          builder: _buildFuture,
          future: _futureBuilderFuture,
        ) /* */
        );
  }

  ///snapshot就是_calculation在时间轴上执行过程的状态快照
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    data = snapshot.data.toString();
    print(data);
    Map<String, dynamic> dataMap = jsonDecode(data);
    bean = WarehousingReturnsEntity.fromJson(dataMap["datas"]);
    exhibitionList.clear();
    for (int i = 0; i < bean.datas.length; i++) {
      if (bean.datas.elementAt(i).state == "未退货") {
        if (selected != 1&&selected != 2) {
          exhibitionList.add(bean.datas[i]);
        }
      } else if (bean.datas.elementAt(i).state == "已退货") {
        if (selected != 0&&selected != 2) {
          exhibitionList.add(bean.datas[i]);
        }
      }else if (bean.datas.elementAt(i).state == "已驳回") {
        if (selected != 0&&selected!=1) {
          exhibitionList.add(bean.datas[i]);
        }
      }
    }
    return LoadBuilder(
        emptyVisibility: exhibitionList.length == 0,
        builder:ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              WarehousingReturnsData data = exhibitionList.elementAt(index);
              return InTaskListWidget<WarehousingReturnsData>(
                context: context,
                index: index,
                data: data,
                type: "入库退货",
              );
            },
            separatorBuilder: (BuildContext context, int index) =>
                Divider(height: 1, color: Colors.transparent),
            itemCount: exhibitionList.length));


  }

  Future _gerData() async {
    var response = InternetAPI.getInstance()
        .dio
        .get("OMS/MiBackProductTask/GetAllMiBackProductTask", queryParameters: {
      'operaterUserId': DataSingleton().Data.id,
      'userId': DataSingleton().Data.id,
      'tenantId': DataSingleton().Data.tenantId,
      'pageNo': -1
    });
    return response;
  }
}
